import os
from datetime import datetime
from typing import Annotated

import typer
from rich.table import Table

from apserver_mgr.shared import init_system, DEFAULT_SYSNO, calculate_md5

app = typer.Typer()


@app.command(name="check")
def apserver_check(
    filename: Annotated[str, typer.Argument(help="要检查的文件")],
    sysno: Annotated[str, typer.Option(help="系统代号")] = DEFAULT_SYSNO,
):
    """
    检查服务器文件。
    """
    console, sysinfo, servers = init_system(sysno)

    table = Table("服务器文件", "校验码", "大小(单位：字节)", "最后修改时间")

    with typer.progressbar(servers) as progress:
        for server in progress:
            target_path = server.apdirectory + "\\" + os.path.basename(filename)
            typer.secho(f"\t检查 {target_path}")

            if os.path.exists(target_path):
                # 获取文件状态信息
                file_stat = os.stat(target_path)

                # 获取最后修改时间
                file_mtime = datetime.fromtimestamp(file_stat.st_mtime)
                formatted_time = file_mtime.strftime("%Y-%m-%d %H:%M:%S")

                # 计算文件MD5
                md5_hash = calculate_md5(target_path)

                table.add_row(
                    target_path, md5_hash, formatted_time, str(file_stat.st_size)
                )

            else:
                table.add_row(target_path, "文件不存在", "", "")

    console.print(table)
